<template>
  <van-popup
    v-model="show"
    position="left"
    class="fa"
    :style="{ height: '100%', width: '100%' }"
  >
    <div>
      <van-nav-bar
        title="报价管理"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
      <!-- v-if="!this.Id" -->
      <div class="client">
        <van-field
          label="客户名称："
          v-model="entity.CustomerName"
          readonly
          @click="CustomerChoice"
          placeholder="请选择客户"
          @click-right-icon="CustomerChoice"
        >
          <!-- right-icon="edit" -->
        </van-field>
        <van-field
          label="价格表名称："
          v-model="entity.PriceListName"
          readonly
          placeholder="请选择价格表"
          @click-right-icon="PriceList"
        >
          <!-- @click="PriceList" -->
          <!-- right-icon="edit" -->
        </van-field>
        <van-field
          readonly
          v-model="entity.Discount"
          label="折扣"
          placeholder="请输入折扣"
        />
        <van-field
          readonly
          v-model="entity.TotalAmount"
          label="折扣后金额"
          placeholder="根据折扣计算"
        />
      </div>
      <div class="scrollBar">
        <div class="Pricebox" v-for="item in data" :key="item.Id">
          <div class="left">
            品名:<span class="font"
              >{{ item.ProductId }}/{{ item.cInvName }}</span
            >
          </div>

          <div class="left">
            规格:<span class="font">{{ item.cInvStd || "无" }}</span>
          </div>
          <span class="Fa">
            <span class="left">数量:</span>
            <van-stepper
              disabled
              @change="ProductIdNum"
              class="fontstepper"
              v-model="item.ProductIdNum"
            />
          </span>
          <div class="Fa">
            <span
              ><van-field
                disabled
                label="税率%:"
                placeholder="税率"
                v-model="item.TaxRate"
            /></span>
            <van-field
              disabled
              label="含税价格:"
              placeholder="价格"
              v-model="item.Tax_Included_Price"
            />
          </div>
        </div>
      </div>
    </div>
    <Myuser @customerChoice="Client" ref="myuser" />
    <PriceList ref="PriceList" @PriceList="Price" />
    <ProductPriceList @Product="Product" ref="product" />
    <div
      :style="{
        position: 'fixed',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '5px 0px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <span class="spanfont"
        >金额合计:
        <div class="price">{{ c }}</div>
      </span>
      <!-- &nbsp;&nbsp;&nbsp;&nbsp; -->
      <div style="margin-top:8px">
        <!-- <van-button @click="Add" slot="button" type="info">添加产品</van-button> -->
        <van-button
          style="margin-left:8px"
          @click="close"
          slot="button"
          type="default"
          >关闭</van-button
        >
        <!-- <van-button
          style="margin:0px 8px"
          @click="handleSubmit"
          slot="button"
          type="primary"
          >保存</van-button
        > -->
      </div>
    </div>
  </van-popup>
</template>

<script>
import { Icon } from "vant";
import { Popup } from "vant";
import { AddressList, Stepper } from "vant";

import { Row, Col, Cell, CellGroup, Toast, NavBar, Divider } from "vant";
import { Field } from "vant";
//客户
import Myuser from "@/components/OwnUser.vue";
import ProductPriceList from "../../components/ProductPriceList.vue";
import PriceList from "../../components/PriceList.vue";

export default {
  watch: {
    data: {
      handler(n, o) {
        //console.log(n, o)
        this.$nextTick(() => {
          //金额
          this.a = 0;

          this.n = 0;
          this.TaxAll = 0;
          n.length > 0 &&
            n.forEach(item => {
              if (Number(item.ProductIdNum) < 0) {
                Toast("数量不能小于0");
                this.$set(item, "ProductIdNum", 1);
              }
              if (Number(item.TaxRate) < 0) {
                Toast("税率不能小于0");
                this.$set(item, "TaxRate", 1);
              }
              if (Number(item.Tax_Included_Price) < 0) {
                Toast("价格不能小于0");
                this.$set(item, "Tax_Included_Price", 1);
              }
              this.j += Number(item.Tax_Included_Price);
              this.n += Number(item.Tax_Excluded_Price);
              //金额
              item.Amounts = item.ProductIdNum * item.Tax_Included_Price;
              //不含税价格
              item.Tax_Excluded_Price =
                (item.Tax_Included_Price / (item.TaxRate / 100 + 1)) *
                item.ProductIdNum;

              //税金
              item.Tax =
                (item.Tax_Included_Price -
                  item.Tax_Included_Price / (item.TaxRate / 100 + 1)) *
                item.ProductIdNum;
              this.TaxAll += Number(item.Tax);
              this.a += Number(item.Amounts);
            });

          this.c = 0;
          if (this.a) {
            let c = this.a
              .toFixed(2)
              .replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, "$&,");
            this.c = c;
          }

          let TotalMomey = 0;
          TotalMomey = this.a * (this.entity.Discount / 100);
          TotalMomey = TotalMomey.toFixed(2).replace(
            /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
            "$&,"
          );
          this.$set(this.entity, "TotalAmount", TotalMomey);
          this.entity.Taxes = this.TaxAll * (this.entity.Discount / 100);
          this.entity.Taxes = this.entity.Taxes.toFixed(2).replace(
            /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
            "$&,"
          );
        });

        //console.log(this.a)
      },
      deep: true,
      immediate: true
    },

    "entity.Freight": {
      handler(newVal, oldVal) {
        //console.log(newVal, oldVal)

        if (newVal < 0) {
          this.$set(this.entity, "Freight", 1);
          return Toast("运费不可以小于0");
        }
      },
      deep: true,
      immediate: true
    },
    "entity.Discount": {
      handler(newVal, oldVal) {
        //console.log(newVal)
        if (newVal > 100) {
          this.$set(this.entity, "Discount", 100);
          return Toast("折扣不可以大于100");
        }
        if (newVal < 0) {
          this.$set(this.entity, "Discount", 1);
          return Toast("折扣不可以小于0");
        }
        if (newVal) {
          let TotalMomey = 0;
          TotalMomey = this.a * (this.entity.Discount / 100);
          TotalMomey = TotalMomey.toFixed(2).replace(
            /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
            "$&,"
          );
          this.$set(this.entity, "TotalAmount", TotalMomey);
          this.entity.Taxes = this.TaxAll * (this.entity.Discount / 100);
          this.entity.Taxes = this.entity.Taxes.toFixed(2).replace(
            /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
            "$&,"
          );
        }
      },
      deep: true,
      immediate: true
    }
  },

  components: {
    "van-stepper": Stepper,
    //分割线
    "van-divider": Divider,
    "van-nav-bar": NavBar,
    "van-icon": Icon,
    "van-popup": Popup,
    "van-row": Row,
    "van-address-list": AddressList,
    "van-field": Field,
    "van-col": Col,
    "van-cell": Cell,
    "van-cell-group": CellGroup,
    Myuser,
    ProductPriceList,
    PriceList
  },
  data() {
    return {
      entity: {},
      data: [],
      show: false,
      IsLadderPrice: false,
      a: 0,
      Id: "",
      TaxAll: 0,
      c: 0
    };
  },
  methods: {
    //返回
    onClickLeft() {
      this.show = false;
    },
    //选中的产品
    // Product(a) {
    //   var ar = [];
    //   a = [a];
    //   this.data.forEach(item => {
    //     a.forEach((val, i) => {
    //       if (item.ProductId == val.ProductId) {
    //         ar.push(val);
    //         delete a[i];
    //       }
    //     });
    //   });
    //   //console.log(ar)

    //   if (ar.length == 0) {
    //     a.forEach(item => {
    //       //console.log(this.data)

    //       this.data.push({
    //         ProductId: item.ProductId,
    //         cInvName: item.cInvName,
    //         cInvCode: item.cInvCode,
    //         cInvStd: item.cInvStd,
    //         Tax_Included_Price: item.StandardPrice,
    //         TaxRate: 13,
    //         ProductIdNum: 1
    //       });
    //     });
    //     //console.log(ar)
    //     // this.data = [...this.data, ...a]
    //   } else {
    //     Toast.fail("重复产品已筛选掉");
    //     a.forEach(item => {
    //       console.log(item);
    //       this.data = [...this.data, item];
    //     });
    //   }
    // },
    Product(a) {
      var ar = [];
      console.log(a);

      a = [a];
      this.data.forEach(item => {
        a.forEach((val, i) => {
          if (item.ProductId == val.cInvCode) {
            ar.push(val);
            delete a[i];
          }
        });
      });
      //console.log(ar)

      if (ar.length == 0) {
        a.forEach(item => {
          this.data.push({
            ProductId: item.cInvCode,
            cInvName: item.cInvName,
            cInvCode: item.cInvCode,
            cInvStd: item.cInvStd,
            TaxRate: 13,
            ProductIdNum: 1,
            Price: item.StandardPrice,
            Tax_Included_Price: item.StandardPrice,
            NumLowerLimit1: item.NumLowerLimit1,
            NumLowerLimit2: item.NumLowerLimit2,
            NumLowerLimit3: item.NumLowerLimit3,
            LowerLimitPrice1: item.LowerLimitPrice1,
            LowerLimitPrice2: item.LowerLimitPrice2,
            LowerLimitPrice3: item.LowerLimitPrice3
          });
        });
        //console.log(ar)
        // this.data = [...this.data, ...a]
      } else {
        Toast.fail("重复产品已筛选掉");
        a.forEach(item => {
          this.data = [...this.data, item];
        });

        //console.log(a)
      }
    },
    // 选择产品;
    Add() {
      if (this.entity.PriceListId) {
        this.$refs.product.openForm(this.entity.PriceListId);
      } else {
        Toast("请先选择价格表");
        return;
      }
    },
    close() {
      this.show = false;
    },
    Client(a) {
      console.log(a);
      this.$set(this.entity, "CustomerName", a.cCusName);
      console.log(this.entity.CustomerName);

      this.entity.CustomerId = a.cCusCode;
    },
    ProductIdNum() {
      console.log(123);
      this.data.forEach(item => {
        if (
          this.IsLadderPrice &&
          Number(item.ProductIdNum) > item.NumLowerLimit1 &&
          item.ProductIdNum <= item.NumLowerLimit2
        ) {
          console.log(123);

          // ...item,
          // Tax_Included_Price: item.LowerLimitPrice1
          item.Tax_Included_Price = item.LowerLimitPrice1.toFixed(2);
        }
        if (
          this.IsLadderPrice &&
          Number(item.ProductIdNum) > item.NumLowerLimit2 &&
          item.ProductIdNum <= item.NumLowerLimit3
        ) {
          item.Tax_Included_Price = item.LowerLimitPrice2.toFixed(2);
        }
        if (
          this.IsLadderPrice &&
          Number(item.ProductIdNum) > item.NumLowerLimit3
        ) {
          item.Tax_Included_Price = item.LowerLimitPrice3.toFixed(2);
        }
        if (
          this.IsLadderPrice &&
          Number(item.ProductIdNum) < item.NumLowerLimit1
        ) {
          item.Tax_Included_Price = item.Price;
        }
      });
    },
    Price(a) {
      console.log(a);
      this.IsLadderPrice = a.IsLadderPrice;
      this.$set(this.entity, "PriceListName", a.ListName);
      this.$set(this.entity, "PriceListId", a.Id);
    },
    PriceList() {
      this.$refs.PriceList.openForm();
    },
    //选择客户
    CustomerChoice() {
      if (!this.Id) this.$refs.myuser.openForm();
    },

    getDataList() {
      this.http
        .post("/QuotationManagement/Quot_OfferSheetMain/GetTheDataOfAll", {
          // PageIndex: this.pagination.current,
          // PageRows: this.pagination.pageSize,
          SortField: "Id",
          SortType: "desc",
          Search: {
            Condition: "Id",
            Keyword: this.Id
          }
        })
        .then(res => {
          if (res.Success) {
            this.entity = res.Data;

            this.data = res.Data.QOSD_List;
          } else {
            Toast(res.Msg);
          }
        });
    },
    init() {
      this.Id = "";
      this.show = true;
      (this.data = []), (this.entity = {});
      this.$set(this.entity, "Discount", 100);
    },
    handleSubmit() {
      var entityData = { ...this.entity };
      var QOSD_List = [...this.data];
      entityData.QOSD_List = QOSD_List;
      // console.log(entityData);
      console.log(entityData.QOSD_List.length);
      if (entityData.QOSD_List.length == 0) {
        Toast("产品不能为空");
        return;
      }
      this.http
        .post("/QuotationManagement/Quot_OfferSheetMain/SaveData", entityData)
        .then(resJson => {
          console.log(resJson);

          if (resJson.Success) {
            Toast(resJson.Msg);
            this.show = false;

            console.log(this.$parent);
            this.$parent.getDataList();
          } else {
            Toast(resJson.Msg);
          }
        });
    },
    openForm(Id) {
      this.init();
      if (Id) {
        this.Id = Id;
        this.getDataList();
      }
    }
  }
};
</script>

<style scoped>
.price {
  color: red;
}
.fontstepper {
  margin-left: 15px;
  line-height: 40px;
}
.spanfont {
  float: left;
  margin-top: 10px;
  line-height: 20px;

  margin-left: 10px;
}
.left {
  margin: 10px 0px 10px 15px;
}
.font {
  margin-left: 15px;
  font-size: 18px;
}
.scrollBar {
  /* height: 550px; */
  height: calc(100vh - 230px);
  /* padding-bottom: 80px; */
  overflow: auto;
}

.client {
  box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 5px 5px;
}
.Pricebox {
  box-shadow: 2px 2px 5px #ccc;
  border-radius: 5px;
  width: 95%;

  margin: 0 auto;

  border: 1px solid #ccc;
  /* box-shadow: rgba(128, 128, 128, 0.1) 10px 10px 10px 10px; */

  margin-top: 20px;
  margin-bottom: 10px;
}
.Fa {
  display: flex;
  justify-content: left;
}
</style>
